package com.atguigu.shiro.handler;

import javax.servlet.http.HttpSession;
import com.atguigu.shiro.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {

    @Autowired
    private ShiroService shiroService;

    @RequestMapping("/testAnnotation")
    public String testAnnotation(HttpSession session){
        session.setAttribute("key","value1");
        shiroService.testMethod();
        return "redirect:/list.jsp";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("name") String name,
                        @RequestParam("password") String password) {

        Subject currentUser = SecurityUtils.getSubject();
		if(!currentUser.isAuthenticated()){
		    //把用户名和密码封装为UsernamePasswordToken对象
            UsernamePasswordToken token = new UsernamePasswordToken(name,password);
            //记住我
            token.setRememberMe(true);
            try {
                //执行登录
                currentUser.login(token);
            } catch (AuthenticationException e) {
               // e.printStackTrace();
                System.out.println("登录失败" + e.getMessage());
            }
        }

        return "redirect:/list.jsp";
    }
}
